import React, { useState } from 'react';
import { useDrop } from 'react-dnd'
import './index.less'
import { useSetRecoilState } from 'recoil'
import { designerState } from '../../../store'
import { IDraggable } from '../component_type'
import { produce } from 'immer';
import { nanoid } from 'nanoid'

interface IProps extends IDraggable {
  dragType: string | Array<string>,
  parent: any
}

export default function DropWrapper (props: IProps) {
  const setPageData = useSetRecoilState(designerState.pageDataAtom);

  const [ collected, drop ] = useDrop({
    accept: props.dragType,
    drop: (item: any, monitor) => {
      // alert(1233)
      // var newItem = {..._item, parent: pid}
      // // 如果已经存在,容器内改变位置
      // if (newItem.sid) {
      //   // 如果拖到自己的父容器里 则不改变,后续要考虑同一个父容器下改变子项的顺序
      //   var opt = undefined
      //   if (_item.parent === pid) {
      //     opt = {
      //       sort: item.sort
      //     }
      //   }
      //   // else {
      //   //   RecoilDataUtil(pageData, setPageData).updateById(newItem, opt)
      //   // }
      //   RecoilDataUtil(pageData, setPageData).updateById(newItem, opt)
      // } else {
      //   RecoilDataUtil(pageData, setPageData).add(newItem)
      // }

      var newItem = produce(item, (draft: any) => {
        draft.meta.id = nanoid()
        draft.meta.parent = props.parent // 设置父 Id
      })
      // debugger

      setPageData((pageData: Array<any>) => [
        ...pageData, newItem
      ])
    },
    collect: (monitor) => {
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
      }
    }
  })

  const isActive = collected.canDrop && collected.isOver
  // const bg = isActive ? '#d9a7d9' : '#d9d9d9';

  return (
    <div ref={ drop } className={ collected.isOver ? 'dropWrapper' : 'no-dropWrapper'}  >
      { props.children }
      <div className='dropWrapper-border'>
        <div className='triangle-left'></div>
        <div className='triangle-right'></div>
      </div>
    </div>
  )
}